//
//  NewsViewController.m
//  GitBucket
//
//  Created by 3024 on 15/11/2.
//  Copyright © 2015年 ios25. All rights reserved.
//

#import "NewsViewController.h"
#import "NewTableViewCell.h"
#import "NewCellModel.h"
#import "JsonData.h"
#import "DetailViewController.h"
@interface NewsViewController ()<UIScrollViewDelegate>
{
    __weak IBOutlet UIActivityIndicatorView *actView;
    //数据源
    NSMutableArray *_dataSourse;
    IBOutlet UITableView *_tableView;
}

@end

@implementation NewsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _dataSourse = [NSMutableArray array];
    //判断数据是否之前有加载过，若有则直接取出，否则网络请求获得数据
    NSString *FilePath =[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"newDataSoure.plist"];
    //反归档取出数据源
    
    if ([[NSData alloc]initWithContentsOfFile:FilePath] != nil) {
        NSData *data = [NSData dataWithContentsOfFile:FilePath];
        _dataSourse = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        NSLog(@"%@",_dataSourse);
    }else{
        //添加自身作为通知的观察者,
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        
        [center addObserver:self selector:@selector(getData) name:@"updateDateSouce" object:nil];
        
        //[self getData];
    }
    
}

//请求数据
-(void)getData
{
    //获取数据源
    JsonData *jsondata = [JsonData allowInitDefault];
    //请求获得数据
    NSArray *events = jsondata.received_events;
    for (NSDictionary *dic in events) {
        NSString *img_avatar_url_str = dic[@"actor"][@"avatar_url"];
        NSString *img_avatar_url_str_long = [NSString stringWithFormat:@"%@?client_id=7222dd6497b25737c70c&client_secret=b507ccb75cd6b99d6759a79ee0b406d13294f4fa",img_avatar_url_str];
        NSURL *img_avatar_url = [NSURL URLWithString:img_avatar_url_str_long];
        UIImage *img_avatar = [UIImage imageWithData:[NSData dataWithContentsOfURL:img_avatar_url]];
        //构建textViewString
        NSMutableString *textViewString = [NSMutableString stringWithFormat:@"      %@",dic[@"actor"][@"login"]];
        //根据type确定如何拼接字符串 //判断type是什么类型赋值image
        NSString *type = dic[@"type"];
        UIImage *typeImage;
        NSString *comment;
        if ([type isEqualToString: @"WatchEvent"]) {
            //星星
            typeImage = [UIImage imageNamed:@"fullStar.png"];
            [textViewString appendFormat:@" starred %@",dic[@"repo"][@"name"]];
            
        }else if ([type isEqualToString:@"ForkEvent"])
        {
            //分支
            typeImage = [UIImage imageNamed:@"smallFork.png"];
            [textViewString appendFormat:@" forked %@ to %@",dic[@"repo"][@"name"],dic[@"payload"][@"forkee"][@"full_name"]];
        }else if ([type isEqualToString:@"CommitCommentEvent"]){
            //评论
            typeImage = [UIImage imageNamed:@"Info.png"];
            
            [textViewString appendFormat:@" commented on comment %@",dic[@"repo"][@"name"]];
            comment = dic[@"payload"][@"comment"][@"body"];
        }else
        {
            //创建
            typeImage = [UIImage imageNamed:@"smallRepo.png"];
            [textViewString appendFormat:@" created repository %@",dic[@"repo"][@"name"]];
            
        }
        //请求下一个界面需要的字典
            NSString *urlString = dic[@"repo"][@"url"];
            NSString *urlString_long = [NSString stringWithFormat:@"%@?client_id=7222dd6497b25737c70c&client_secret=b507ccb75cd6b99d6759a79ee0b406d13294f4fa",urlString];
            NSURL *contentUrl = [NSURL URLWithString:urlString_long];
            NSData *data = [NSData dataWithContentsOfURL:contentUrl];
            NSDictionary *contentDic = [NSDictionary new];
            contentDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"contentDic:%@",contentDic);
        NewCellModel *model = [NewCellModel allocInitModel:img_avatar typeImage: typeImage textViewString:textViewString comment:comment date:dic[@"created_at"] aNewdic:contentDic];
        
        [_dataSourse addObject:model];
    }
    
    //将数据源保存到本地，以便下次可以直接访问
    NSString *FilePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"newDataSoure.plist"];
    //保存
    //2.归档器类提供"一句话归档"的类方法
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:_dataSourse];
    //归档完成写入文件
    if ([data writeToFile:FilePath atomically:YES]) {
        NSLog(@"写入newDataSoure成功");
    }
    //取得数据后更新数据源
    [actView stopAnimating];
    [_tableView reloadData];
}

-(void)viewWillAppear:(BOOL)animated
{
    //显示底部
    self.tabBarController.tabBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataSourse.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"newsCell"];
    cell.model = _dataSourse[indexPath.row];
    return cell;
}

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    NewTableViewCell *cell = sender;
    DetailViewController *dtvc = segue.destinationViewController;
    dtvc.dataDic = cell.dataDic;
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //查看移动的偏移量
    //    CGPoint offset = scrollView.contentOffset;
    
    //    NSLog(@"did scroll %lf,%lf",offset.x,offset.y);
    //
    //    if (offset.y < -100) {
    //        [self getData];
    //    }
    
}
- (void)dealloc
{
    //移除通知观察者
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    
}
@end
